﻿
//Global variables
this.$ajax = {
    getJSON: $.getJSON
};
this.data = null;

function transformToTimeseries(data) {
    var timeseries = [];

    for (i in data) {
        label = data[i].Label;
        name = data[i].Id;
        existingTimeseries = findByNameIn(timeseries, name);
        if (existingTimeseries == null)
            timeseries.push({ name: name, label: label, values: [], totalTime: [], userTime: [], systemTime: [], realTime: [] });
    }

    for (i in data) {
        name = data[i].Id;
        label = data[i].Label;
        totalTime = data[i].TotalTime;
        timestamp = data[i].Timestamp;  
        userTime = data[i].UserTime;
        systemTime = data[i].SystemTime;
        realTime = data[i].RealTime;
        if (typeof(timestamp) == "string")
            timestamp = eval(timestamp.replace(/\/Date\((\d*)\+\d*\)\//, "new Date($1)"));

        ts = findByNameIn(timeseries, name);
        ts.values.push({ date: timestamp, totaltime: totalTime });
        ts.totalTime.push([timestamp, totalTime]);
        ts.userTime.push([timestamp, userTime]);
        ts.systemTime.push([timestamp, systemTime]);
        ts.realTime.push([timestamp, realTime]);
    }
    
    return timeseries;
}

function findByNameIn(array, name) {
    for (i in array) {
        if (array[i].name.toString() == name.toString())
            return array[i];
    }
        return null;
}

function initializeReport() {
    var contentContainer = $("#content");
    if (contentContainer.length == 0) {
        $("body").append("<div id=\"content\"></div>");
    }

    $ajax.getJSON("measurements.quickbencher", function(result) {
        data = result
        timeseries = transformToTimeseries(data);
        for (i in timeseries) {
            ts = timeseries[i];
            $("#content").append("<h1>" + ts.label + "</h1>");
            $("#content").append("<div id=\"" + ts.name + "\"></div>");
            $("#" + ts.name).css({
                width: 1000,
                height: 400,
                "margin-bottom": 20,
            });

            $.plot($("#" + ts.name), [
                    { label: "TotalTime", data: ts.totalTime}, 
                    { label: "UserTime", data: ts.userTime },
                    { label: "SystemTime", data: ts.systemTime },
                    { label: "RealTime", data: ts.realTime }
                ], {
                xaxis: { mode: "time" }
            });
        }
    });
}